package bootstrap

import (
	"gitee.com/xlizy/common-go/base/common_config"
	"gitee.com/xlizy/common-go/base/common_goroutine"
	"gitee.com/xlizy/common-go/components/dlock"
	"gitee.com/xlizy/common-go/components/nacos/v2"
	"gitee.com/xlizy/common-go/components/nacos_grpc"
	"gitee.com/xlizy/common-go/utils/iris"
	"gitee.com/xlizy/common-go/utils/snowflake"
	"gitee.com/xlizy/common-go/utils/zlog"
	"os"
	"os/signal"
	"syscall"
)

// Init 项目启动引导初始化方法
func Init() {
	//初始化日志组件
	zlog.InitLogger(common_config.GetLogCfg().Path)
	//初始化雪花算法组件(id生成器)
	snowflake.Init(1, 1)
	//打印项目启动日志
	zlog.Info("项目开始启动...")
	//所有服务均使用nacos作为服务发现中心和配置中心，所以需要先初始化nacos
	nacos.InitNacos()
}

// GracefulShutdown 优雅关闭各个组件
func GracefulShutdown(other func()) {
	// 等待中断信号以优雅地关闭服务器
	stop := make(chan os.Signal, 1)
	signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
	// 阻塞，直到接收到信号
	<-stop

	zlog.Info("关闭服务组件,释放资源...")

	nacos_grpc.GracefulShutdown()
	nacos.GracefulShutdown()
	iris_util.GracefulShutdown()
	nacos.GetCronManage().Stop()
	common_goroutine.GracefulShutdown()
	dlock.GracefulShutdown()

	other()
}
